@tool
extends StaticBody2D

@export var move_distance:float = 180
@export var move_time:float = 0.5
@export var move_dir:Vector2 = Vector2.RIGHT
@export var sprite_rotation:float

var is_activity:bool = false
var _move_start: Vector2
var _move_end: Vector2
var _moving_to_end: bool = true

@onready var down_ray_cast: RayCast2D = $DownRayCast
@onready var right_ray_cast: RayCast2D = $RightRayCast
@onready var up_ray_cast: RayCast2D = $UpRayCast
@onready var left_ray_cast: RayCast2D = $LeftRayCast
@onready var sprite_2d: Sprite2D = $Sprite2D


func _process(delta: float) -> void:
	if not Engine.is_editor_hint():
		var triggered = false
		sprite_2d.rotation = deg_to_rad(sprite_rotation)
		if Engine.get_process_frames() % 5 == 0:
			var rays = [down_ray_cast, right_ray_cast, up_ray_cast, left_ray_cast]
			var dirs = [Vector2.DOWN.rotated(rotation), Vector2.RIGHT.rotated(rotation), Vector2.UP.rotated(rotation), Vector2.LEFT.rotated(rotation)]
			for i in range(rays.size()):
				var ray = rays[i]
				if ray.is_colliding():
					var obj = ray.get_collider()
					if obj and obj.has_method("with_move") and obj.get_parent() != self:
						var global_pos = ray.global_position + dirs[i] * 55
						obj.get_parent().remove_child(obj)
						add_child(obj)
						obj.global_position = global_pos
						obj.with_move()
						triggered = true
		# 仅第一次吸附后启动移动
		if triggered and not is_activity:
			is_activity = true
			_move_start = global_position
			_move_end = global_position + move_dir.normalized() * move_distance
			_moving_to_end = true
			_start_move()
	else:
		sprite_2d.rotation = deg_to_rad(sprite_rotation)


func _start_move():
	var from_pos = _move_start if _moving_to_end else _move_end
	var to_pos = _move_end if _moving_to_end else _move_start
	var tween = create_tween()
	tween.tween_property(self, "global_position", to_pos, move_time)
	tween.tween_callback(func():
		_moving_to_end = !_moving_to_end
		_start_move()
	)
		
